import {
  AccountInfo,
  CommonUserInfo,
} from '@/api/userCenter/authority/model/accountModel'
import { MutationTree } from 'vuex'
import { setItem, removeItem } from '@/utils/storage'
import { AccountState } from './index'
import { getButtonPerm, installApiRoute } from '@/utils/routeHelper'
import router from '@/router'

export enum AccountMutationTypes {
  /** 保存账号信息 */
  SAVE_ACCOUNT_INFO = 'SAVE_ACCOUNT_INFO',
  /** 删除账号信息 */
  DELETE_ACCOUNT_INFO = 'DELETE_ACCOUNT_INFO',
  /**保存当前账号菜单列表信息 */
  SAVE_MENU_LIST = 'SAVE_MENU_LIST',
  /** 删除当前账号菜单信息 */
  DELETE_MENU_LIST = 'DELETE_MENU_LIST',
  /** 更新用户基本信息 */
  UPDATE_COMMON_USERINFO = 'UPDATE_COMMON_USERINFO',
}

export interface AccountMutations<S = AccountState> {
  [AccountMutationTypes.SAVE_ACCOUNT_INFO]: (
    state: S,
    payLoad: AccountInfo
  ) => void
  [AccountMutationTypes.DELETE_ACCOUNT_INFO]: (state: S) => void
  [AccountMutationTypes.SAVE_MENU_LIST]: (state: S, payLoad: string) => void
  [AccountMutationTypes.DELETE_MENU_LIST]: (state: S) => void
  [AccountMutationTypes.UPDATE_COMMON_USERINFO]: (
    state: S,
    newUserInfo: CommonUserInfo
  ) => void
}

const mutations: MutationTree<AccountState> & AccountMutations = {
  SAVE_ACCOUNT_INFO: (state, userInfo) => {
    // 保存用户信息
    state.currentUser = userInfo
    setItem('currentUser', userInfo)
    // 筛出并保存用户按钮权限
    const btnPerms = getButtonPerm(userInfo.perms)
    state.actionList = btnPerms
    setItem('actionList', btnPerms)
  },
  DELETE_ACCOUNT_INFO: (state) => {
    state.currentUser = undefined
    state.clientId = ''
    state.actionList = []
    removeItem('currentUser')
    removeItem('clientId')
    removeItem('actionList')
  },
  SAVE_MENU_LIST: (state, appId) => {
    state.clientId = appId
    setItem('clientId', appId)
    if (state.currentUser && state.currentUser.perms) {
      state.menuList =
        state.currentUser.perms.find((item) => item.id === appId)?.children ||
        []
    }
    setItem('menuList', state.menuList)

    // 添加当前存储的路由
    installApiRoute(router, 'home', state.menuList)
  },
  DELETE_MENU_LIST: (state) => {
    state.menuList = []
    removeItem('menuList')
  },
  UPDATE_COMMON_USERINFO: (state, newUserInfo) => {
    if (state.currentUser && state.currentUser.user) {
      state.currentUser.user.avatar = newUserInfo.avatar
      state.currentUser.user.mail = newUserInfo.mail
      state.currentUser.user.phone = newUserInfo.phone
      state.currentUser.user.name = newUserInfo.name
      setItem('currentUser', state.currentUser)
    }
  },
}

export default mutations
